package grdnlog.dao;

import grdnlog.bean.GardenLogEntry;

import java.util.Date;
import java.util.List;

import javax.persistence.EntityManager;
import javax.persistence.Query;

import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;

public class GardenLogEntryDao extends JpaDao<GardenLogEntry> {

	@Override
	public Class<GardenLogEntry> getEntityClass() {
		return GardenLogEntry.class;
	}

	@SuppressWarnings("unchecked")
	@Transactional(propagation = Propagation.REQUIRED)
	public List<GardenLogEntry> get(String userId) {
		final EntityManager entityManager = getEntityManager();
		final StringBuilder builder = new StringBuilder("SELECT o FROM ").append(getEntityClass().getName()).append(" o");
		builder.append(" WHERE o.userId = ?1 ORDER BY o.date DESC");
		
		final Query query = entityManager.createQuery(builder.toString());
		query.setParameter(1, userId);
		
	    return query.getResultList();
	}
	
	@SuppressWarnings("unchecked")
	@Transactional(propagation = Propagation.REQUIRED)
	public List<GardenLogEntry> get(String userId, Date fromDate, Date toDate) {
		final EntityManager entityManager = getEntityManager();
		final StringBuilder builder = new StringBuilder("SELECT o FROM ").append(getEntityClass().getName()).append(" o");
		builder.append(" WHERE o.userId = ?1 AND o.date BETWEEN ?2 AND ?3 ORDER BY o.date DESC");
		
		final Query query = entityManager.createQuery(builder.toString());
		query.setParameter(1, userId);
		query.setParameter(2, fromDate);
		query.setParameter(3, toDate);
		
	    return query.getResultList();
	}

}
